package cn.zlh.ht.controller;

import cn.zlh.basics.baseVo.Result;
import cn.zlh.basics.utils.ResultUtil;
import cn.zlh.ht.entity.Agreement;
import cn.zlh.ht.entity.Template;
import cn.zlh.ht.service.TemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@Api(tags = "合同模板接口")
@RequestMapping("/zlh/template")
@Transactional
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @PostMapping("/createTemplate")
    @ApiOperation(value = "新增模板")
    public Result<Object> createTemplate(@RequestParam Map<String, String> params) {

        String tableName = params.get("tableName");
        String tableCN = params.get("tableCN");

        // 恢复 fields 为 Map
        Map<String, String> fields = new HashMap<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            // 只处理以 fields[开头的字段
            if (entry.getKey().startsWith("fields[")) {
                String key = entry.getKey().substring(7, entry.getKey().length() - 1);  // 去掉 fields[ 和 ]
                fields.put(key, entry.getValue());
            }
        }

        // 构造 Template 对象
        Template template = Template.builder()
                .tableName(tableName)
                .tableCN(tableCN)
                .fields(fields)
                .build();

        templateService.createTemplate(template);
        return ResultUtil.success();
    }

    @GetMapping("/displayTemplate")
    @ApiOperation(value = "展示模板")
    public Result<Object> getAllTemplateColumn() {
        return new ResultUtil<Object>().setData(templateService.getAllTemplateColumn());
    }

    @PostMapping("/insertData")
    @ApiOperation(value = "插入数据")
    public Result<Object> insertData(@RequestBody Template template) {
        templateService.insertData(template);
        return ResultUtil.success();
    }

    @PostMapping("/getTemplateDataByAgreemetnId")
    @ApiOperation(value = "获取模板数据")
    public Result<Object> getTemplateDataByAgreemetnId(String tableName, String agreementId) {
        return new ResultUtil<Object>().setData(templateService.getTemplateDataByAgreemetnId(tableName, agreementId));
    }
}
